<?php 


class WriteToFile{

	private $_fp=null;
	private $message='';
	function __construct($file=null,$mode='c+')
	{
		$this->message="File:$file Mode :$mode";
		if(empty($file))
		throw new FileException($this->message,0);
		if(!file_exists($file))
		throw new FileException($this->message,1);
		if(!is_file($file))
		throw new FileException($this->message,2);
	    if(!is_writable($file))
	    throw new FileException($this->message,3);
	    if(!array($mode,array('a','a+','w','w+','c+')))
	    throw new FileException($this->message,4);
		$this->_fp=fopen($file,$mode);
	}
	function write($data){

		if(@!fwrite($this->_fp, $data."\n")){

			throw new FileException($this->message."Data:$data",5);
			
		}
	}
	function close(){

		if($this->_fp){

			if(@!fclose($this->_fp))
				throw new FileException($this->message,6);
			$this->_fp=null;
		}
	}
	function __destruct(){

		$this->close();
	}
}
class FileException extends Exception{

	function getDetail()
	{
		switch($this->code)
		{
			case 0:
			return 'no filename was provided';
			break;
			case 1:
			return 'the file does not exist';
			break;
			case 2:
			return 'the file is not a file';
			break;
			case 3:
			return 'the file is not writable';
			break;
			case 4:
			return 'An invalid mode was provided';
			break;
			case 5:
			return 'the data could not be written';
			break;
			case 6:
			return ' the file is not be closed';
			break;
			default:
			return 'no further information is availale';
			break;
		}

	}
}
 ?>